package org.jeecg.modules.lab.entrust.controller;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.system.query.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.TokenServess;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.entrust.entity.LabWentrust;
import org.jeecg.modules.lab.entrust.entity.LabWsupervise;
import org.jeecg.modules.lab.entrust.service.ILabWsuperviseService;
import org.jeecg.modules.lab.entrust.vo.LabEntrustPage;
import org.jeecg.modules.lab.entrust.vo.LabSupervisePage;
import org.jeecg.modules.lab.items.entity.LabItems;
import org.jeecg.modules.lab.items.item.service.ILabItemsService;
import org.jeecg.modules.lab.items.task.service.ILabTaskAllotService;
import org.jeecg.modules.lab.items.vo.LabAdutiUserPage;
import org.jeecg.modules.lab.notify.entity.LabNotify;
import org.jeecg.modules.lab.notify.service.ILabNotifyService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 监督抽查表
 * @Author: jeecg-boot
 * @Date: 2023-09-18
 * @Version: V1.0
 */
@Api(tags = "监督抽查表")
@RestController
@RequestMapping("/entrust/labWsupervise")
@Slf4j
public class LabWsuperviseController extends JeecgController<LabWsupervise, ILabWsuperviseService> {
    @Autowired
    private ILabWsuperviseService labWsuperviseService;

    @Autowired
    private ILabTaskAllotService labTaskAllotService;

    @Autowired
    private ILabCronJobService labCronJobService;

    @Autowired
    private ILabNotifyService labNotifyService;

    /**
     * 分页列表查询
     *
     * @param labWsupervise
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "监督抽查表-分页列表查询", notes = "监督抽查表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<LabWsupervise>> queryPageList(LabWsupervise labWsupervise,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "50") Integer pageSize,
                                                      HttpServletRequest req) {
        //QueryWrapper<LabWsupervise> queryWrapper = QueryGenerator.initQueryWrapper(labWsupervise, req.getParameterMap());
        QueryWrapper<LabWsupervise> queryWrapper = new QueryWrapper<>();
        if (labWsupervise.getEntName() != null) {
            String entName = labWsupervise.getEntName();
            queryWrapper.like("ent_name", "%" + entName + "%");
        }
        if (labWsupervise.getTailName() != null) {
            String entName = labWsupervise.getTailName();
            String replace = entName.replace("*", "");
            queryWrapper.like("tail_name", "%" + replace + "%");
        }
        if (labWsupervise.getTailFactory() != null) {
            String entName = labWsupervise.getTailFactory();
            String replace = entName.replace("*", "");
            queryWrapper.like("tail_factory", "%" + replace + "%");
        }
        if (labWsupervise.getTailDate() != null) {
            Date tailDate = labWsupervise.getTailDate();
            queryWrapper.eq("tail_date", tailDate);
            //queryWrapper.like("tail_date",tailDate);
        }
        String auditMark = labWsupervise.getAuditMark();
        if (auditMark != null && !"".equals(auditMark)) {
            queryWrapper.eq("audit_mark", auditMark);
        }
        queryWrapper.orderByDesc("create_time");
        Page<LabWsupervise> page = new Page<LabWsupervise>(pageNo, pageSize);
        IPage<LabWsupervise> pageList = labWsuperviseService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param labSupervisePage
     * @return
     */
    @AutoLog(value = "监督抽查表-添加")
    @ApiOperation(value = "监督抽查表-添加", notes = "监督抽查表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody LabSupervisePage labSupervisePage) {
        LabWsupervise labWsupervise = new LabWsupervise();
        BeanUtils.copyProperties(labSupervisePage, labWsupervise);
        Date day = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        labWsupervise.setHandlDate(DateUtils.date2Str(sdf));
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        labWsupervise.setHandler(loginUser.getRealname());
        labWsuperviseService.saveMain(labWsupervise, labSupervisePage.getLabSampleList());

        if (MyEnum.sync) {
            List<LabCronJob> jobs = new ArrayList<>();
            long time = new Date().getTime();
            jobs.add(new LabCronJob("lab_wsupervise", "0", time, 1));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param labSupervisePage
     * @return
     */
    @AutoLog(value = "监督抽查表-编辑")
    @ApiOperation(value = "监督抽查表-编辑", notes = "监督抽查表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody LabSupervisePage labSupervisePage) {
        LabWsupervise labWsupervise = new LabWsupervise();
        BeanUtils.copyProperties(labSupervisePage, labWsupervise);
        LabWsupervise labWsuperviseEntity = labWsuperviseService.getById(labWsupervise.getId());
        if (labWsuperviseEntity == null) {
            return Result.error("未找到对应数据");
        }
        labWsuperviseService.updateMain(labWsupervise, labSupervisePage.getLabSampleList());

        if (MyEnum.sync) {
            List<LabCronJob> jobs = new ArrayList<>();
            long time = new Date().getTime();
            jobs.add(new LabCronJob("lab_wsupervise", "1", time, 1));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "监督抽查表-通过id删除")
    @ApiOperation(value = "监督抽查表-通过id删除", notes = "监督抽查表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        labWsuperviseService.delMain(id);

        if (MyEnum.sync) {
            List<LabCronJob> jobs = new ArrayList<>();
            long time = new Date().getTime();
            //删除条件
            String condition1 = "entrust_id = '" + id + "'";
            String condition2 = "id = '" + id + "'";
            jobs.add(new LabCronJob("lab_entrust_sample", "2", condition1, time, 1));
            jobs.add(new LabCronJob("lab_wsupervise", "2", condition2, time, 2));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "监督抽查表-批量删除")
    @ApiOperation(value = "监督抽查表-批量删除", notes = "监督抽查表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.labWsuperviseService.delBatchMain(Arrays.asList(ids.split(",")));

        if (MyEnum.sync) {
            List<LabCronJob> jobs = new ArrayList<>();
            long time = new Date().getTime();
            String[] idList = ids.split(",");
            for (int i = 0; i < idList.length; i++) {
                String condition1 = "id='" + idList[i] + "'";
                String condition2 = "entrust_id='" + idList[i] + "'";
                jobs.add(new LabCronJob("lab_wsupervise", "2", condition1, time));
                jobs.add(new LabCronJob("lab_entrust_sample", "2", condition2, time));
            }
            for (int i = 0; i < jobs.size(); i++) {
                jobs.get(i).setOrderNum(i + 1);
            }
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "监督抽查表-通过id查询", notes = "监督抽查表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<LabWsupervise> queryById(@RequestParam(name = "id", required = true) String id) {
        LabWsupervise labWsupervise = labWsuperviseService.getById(id);
        if (labWsupervise == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(labWsupervise);
    }


    /**
     * 监督抽样提交
     *
     * @param id
     * @return
     */
    @AutoLog(value = "监督抽样表-监督抽样提交")
    @ApiOperation(value = "监督抽样表-监督抽样提交", notes = "监督抽样表-监督抽样提交")
    @DeleteMapping(value = "/submitSupervise")
    public Result<String> submitSupervise(@RequestParam(name = "id", required = true) String id) throws NoSuchAlgorithmException, IOException, InvalidKeyException {
        LabWsupervise labWsupervise = labWsuperviseService.getById(id);
        if (labWsupervise == null) {
            return Result.error("未找到对应数据");
        }


        List<LabAdutiUserPage> labAdutiUsers = labTaskAllotService.queryAduitUsers(id);
        String nameStr = "";
        if (labAdutiUsers != null) {
            for (LabAdutiUserPage user : labAdutiUsers) {
                if ("".equals(nameStr)) {
                    nameStr = user.getUName();
                } else {
                    nameStr = nameStr + "," + user.getUName();
                }
            }
        }

        labWsupervise.setAuditMark("审核中");
        labWsupervise.setSynFlag("1");
        labWsupervise.setFinalAudit(nameStr);
        labWsuperviseService.updateById(labWsupervise);

        for (int i = 0; i < labAdutiUsers.size(); i++) {
            LabAdutiUserPage userPage = labAdutiUsers.get(0);

            LabNotify labNotify = new LabNotify();
            labNotify.setNotName("监督抽查审核");
            labNotify.setItemName("");
            labNotify.setNotTitlle("监督");
            //todo:确认taskid是项目的id
            labNotify.setTaskId(userPage.getTId());
            String taskName ="您有一条监督抽查单待审核，请尽快前往[实验室系统]进行办理！";
            labNotify.setTaskName(taskName);
            labNotify.setEntrustId(userPage.getTId());
            labNotify.setUserId(userPage.getUtId());
            labNotify.setNotStatus("未读");
            labNotify.setFinish(0);
            labNotify.setPubTime(new Date());
            labNotifyService.save(labNotify);

            String tId = userPage.getUtId();
            if (!"".equals(tId) && tId != null) {
                TokenServess tokenServess = new TokenServess();
                String tokenServe = tokenServess.getTokenServe();
                tokenServess.getSysmw(taskName, tId, tokenServe);
            }
        }

        if (MyEnum.sync) {
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_notify", "0", time, 1));
            jobs.add(new LabCronJob("lab_wsupervise", "0", time, 2));
            labCronJobService.saveBatch(jobs);
        }

        return Result.OK("提交成功！");
    }

    /**
     * 监督抽样审核通过
     *
     * @param labSupervisePage
     * @return
     */
    @AutoLog(value = "监督抽样表-审核通过")
    @ApiOperation(value = "监督抽样表-审核通过", notes = "监督抽样表-审核通过")
    @RequestMapping(value = "/auditSupervise", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> auditSupervise(@RequestBody LabSupervisePage labSupervisePage) {

        LabWsupervise labWsupervise = new LabWsupervise();
        BeanUtils.copyProperties(labSupervisePage, labWsupervise);
        LabWsupervise labWsuperviseEntity = labWsuperviseService.getById(labWsupervise.getId());
        if (labWsuperviseEntity == null) {
            return Result.error("未找到对应数据");
        }
        labWsupervise.setSynFlag("1");
        labWsuperviseService.auditSupervise(labWsupervise);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            //默认还没有同步数据
            jobs.add(new LabCronJob("lab_wsupervise", "1", time, 1));
            jobs.add(new LabCronJob("lab_entrust_sample", "0", time, 2));
            jobs.add(new LabCronJob("lab_entrust_items", "0", time, 3));
            jobs.add(new LabCronJob("lab_entrust_items_index", "0", time, 4));
            jobs.add(new LabCronJob("lab_items_record_sample", "0", time, 5));
            jobs.add(new LabCronJob("lab_items_record_norm", "0", time, 6));
            jobs.add(new LabCronJob("lab_items_record_target", "0", time, 7));
            jobs.add(new LabCronJob("lab_items_record_person", "0", time, 8));
            jobs.add(new LabCronJob("lab_sample_record", "0", time, 9));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("审核通过！");
    }

    /**
     * 审核退回
     *
     * @param labSupervisePage
     * @return
     */
    @AutoLog(value = "监督抽样表-审核退回")
    @ApiOperation(value = "监督抽样表-审核退回", notes = "监督抽样表-审核退回")
    @RequestMapping(value = "/auditBack", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> auditBack(@RequestBody LabSupervisePage labSupervisePage) {
        LabWsupervise labWsupervise = new LabWsupervise();
        BeanUtils.copyProperties(labSupervisePage, labWsupervise);
        LabWsupervise labWsuperviseEntity = labWsuperviseService.getById(labWsupervise.getId());
        if (labWsuperviseEntity == null) {
            return Result.error("未找到对应数据");
        }
        labWsupervise.setAuditMark("审核退回");
        labWsupervise.setSynFlag("1");
        labWsuperviseService.updateById(labWsupervise);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            ArrayList<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_wsupervise", "1", time, 1));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("退回成功!");
    }


    /**
     * 监督单撤销
     *
     * @param id
     * @return
     */
    @AutoLog(value = "监督抽样表-监督单撤销")
    @ApiOperation(value = "监督抽样表-监督单撤销", notes = "监督抽样表-监督单撤销")
    @DeleteMapping(value = "/cancelOneEnt")
    public Result<String> cancelOneEnt(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "auditMark", required = true) String auditMark) {

        LabWsupervise labWsupervise = labWsuperviseService.getById(id);
        if (labWsupervise == null) {
            return Result.error("未找到对应数据");
        }
        labWsupervise.setAuditMark("审核退回");
        labWsupervise.setSynFlag("1");
        labWsuperviseService.updateById(labWsupervise);


        if (MyEnum.sync) {
            //同步表信息
            long time = new Date().getTime();
            LabCronJob cronJob = new LabCronJob("lab_wsupervise", "1", time, 1);
            labCronJobService.save(cronJob);
        }
        return Result.OK("撤销成功！");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param labWsupervise
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabWsupervise labWsupervise) {
        return super.exportXls(request, labWsupervise, LabWsupervise.class, "监督抽查表");
    }



    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    protected Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<LabWsupervise> list = ExcelImportUtil.importExcel(file.getInputStream(), LabWsupervise.class, params);
                labWsuperviseService.importSaveMain(list);
                if (MyEnum.sync) {
                    long time = new Date().getTime();
                    List<LabCronJob> jobs = new ArrayList<>();
                    //默认还没有同步数据
                    jobs.add(new LabCronJob("lab_wsupervise", "0", time, 1));
                    labCronJobService.saveBatch(jobs);
                }
                return Result.ok("文件导入成功！数据行数：" + (list.size()-1));
            } catch (Exception e) {
                String msg = e.getMessage();
                log.error(msg, e);
                if(msg!=null && msg.indexOf("Duplicate entry")>=0){
                    return Result.error("文件导入失败:有重复数据！");
                }else{
                    return Result.error("文件导入失败:" + e.getMessage());
                }
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");

    }

}
